const express = require('express');
const app = express();
var server = require('http').Server(app);
const io = require('socket.io')(server);
const redis = require("redis").createClient();
const fs = require('fs');
const crypto = require('crypto');
const Buffer = require("buffer").Buffer;

let sockets = [];

server.listen(8889);

app.use(express.static('public'));

redis.on('error', function (err) {
    console.log('Error ' + err);
});

io.on('connect', (socket) => {
    // 保存 socket
    sockets.push(socket);

    // 给当前连接添加 mac address 标识
    socket.on('mac', (data) => {
        socket.mac = data.mac;
    });

    // 根据 mac address 获取用户信息
    socket.on('user', (data) => {
        redis.hgetall(data.mac, (err, replies) => {
            socket.emit('user', replies);
        });
    });

    // 根据 mac address 获取其他用户信息
    socket.on('other user', (data) => {
        redis.hgetall(data.mac, (err, replies) => {
            if (replies !== null) {
                replies.address = data.extra.address;
                replies.rssi = data.extra.rssi;
                socket.emit('other user', replies);
            }
            
        });
    });
    
    // 更新用户名
    socket.on('update user name', (data) => {
        if (socket.mac) {
            redis.hset(socket.mac, 'name', data.name);
        }
    });

    // 更新用户简介
    socket.on('update user intro', (data) => {
        if (socket.mac) {
            redis.hset(socket.mac, 'intro', data.intro);
        }
    });

    // 用户头像
    socket.on('upload avatar', (file) => {
        const base64Data = file.replace(/^data:image\/\w+;base64,/, "");
        const dataBuffer = new Buffer(base64Data, 'base64');
        const avatarName = md5(socket.mac) + '.jpg';

        fs.writeFile('public/avatars/' + avatarName, dataBuffer, (err) => {
            if (!err) {
                redis.hset(socket.mac, 'avatar', avatarName);
            }
        });
    });

    socket.on('message', (data) => {
        redis.hgetall(socket.mac, (err, replies) => {
            data.macs.forEach((ele) => {
                const s = sockets.find((value) => {
                    return value.mac === ele;
                });
                if (s !== -1 && s) {
                    s.emit('message', {user: replies, message: data.message});
                }
            });
        });
    });

    // 失去连接时，删除当前连接
    socket.on('disconnect', () => {
        const currentIndex = sockets.findIndex((value) => {
            return value == socket;
        });
        if (currentIndex !== -1) {
            sockets.splice(currentIndex, 1);
        }
    });

    function md5(data) {
        var buf = new Buffer(data);
        var str = buf.toString("binary");
        return crypto.createHash("md5").update(str).digest("hex");
    }

});